using Senparc.Weixin.Exceptions;
using Senparc.Weixin.QY.Entities;
using System;
using System.Collections.Generic;
namespace Senparc.Weixin.QY.CommonAPIs
{
	public class AccessTokenContainer
	{
		private static Dictionary<string, AccessTokenBag> AccessTokenCollection = new Dictionary<string, AccessTokenBag>(StringComparer.OrdinalIgnoreCase);
		public static void Register(string corpId, string corpSecret)
		{
			AccessTokenContainer.AccessTokenCollection[corpId] = new AccessTokenBag
			{
				CorpId = corpId,
				CorpSecret = corpSecret,
				ExpireTime = DateTime.MinValue,
				AccessTokenResult = new AccessTokenResult()
			};
		}
		public static string TryGetToken(string corpId, string corpSecret, bool getNewToken = false)
		{
			if (!AccessTokenContainer.CheckRegistered(corpId) || getNewToken)
			{
				AccessTokenContainer.Register(corpId, corpSecret);
			}
			return AccessTokenContainer.GetToken(corpId, false);
		}
		public static string GetToken(string corpId, bool getNewToken = false)
		{
			return AccessTokenContainer.GetTokenResult(corpId, getNewToken).access_token;
		}
		public static AccessTokenResult GetTokenResult(string corpId, bool getNewToken = false)
		{
			if (!AccessTokenContainer.AccessTokenCollection.ContainsKey(corpId))
			{
				throw new WeixinException("此CorpId尚未注册，请先使用AccessTokenContainer.Register完成注册（全局执行一次即可）！");
			}
			AccessTokenBag accessTokenBag = AccessTokenContainer.AccessTokenCollection[corpId];
			lock (accessTokenBag.Lock)
			{
				if (getNewToken || accessTokenBag.ExpireTime <= DateTime.Now)
				{
					accessTokenBag.AccessTokenResult = CommonApi.GetToken(accessTokenBag.CorpId, accessTokenBag.CorpSecret);
					accessTokenBag.ExpireTime = DateTime.Now.AddSeconds(7200.0);
				}
			}
			return accessTokenBag.AccessTokenResult;
		}
		public static bool CheckRegistered(string corpId)
		{
			return AccessTokenContainer.AccessTokenCollection.ContainsKey(corpId);
		}
	}
}
